package com.doubi;

import com.jcraft.jsch.*;

import java.io.*;
import java.util.Properties;

/**
 * ssh服务器
 **/
public class SFTPUtil {

    /**
     * Sftp
     */
    private static Session sshSession = null;
    /**
     * 主机
     */
    private String host = "";
    /**
     * 端口
     */
    private int port = 0;
    /**
     * 用户名
     */
    private String username = "";
    /**
     * 密码
     */
    private String password = "";

    public SFTPUtil(String host, int port, String username, String password) {
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
    }

    /**
     * 连接sftp服务器
     */
    private boolean connect() {
        JSch jsch = new JSch();
        try {
            sshSession = jsch.getSession(this.username, this.host, this.port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect(60000);
            return true;
        } catch (JSchException e) {
            e.printStackTrace();
            return false;
        }


    }

    //本地文件路径
    private static final String LOCAT_FILE = "/admin-controller/target/admin-controller-0.0.1.jar";

    public static void main(String[] args){
        try {
            SFTPUtil sftpUtil = new SFTPUtil("106.12.188.232", 22, "root", "shuoxun#123");
            if (sftpUtil.connect()) {
                System.out.println("链接成功-----------------------------》");
                //进入指定路径
                if (uploadFiles()) {
                    runCmd("java -version");
                    Thread.sleep(500);
                    runCmd("source /etc/profile");
                    Thread.sleep(1000);
                    runCmd("killall java");
                    Thread.sleep(2000);
                    runCmd("nohup java -jar /root/admin-controller-0.0.1.jar --spring.profiles.active=test > nohup.log 2>&1 &");
                } else {
                    System.out.println("文件上传失败！");
                }
            } else {
                System.err.println("链接服务器失败！");
            }
            System.out.println("结束");
            System.exit(1);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean uploadFiles() throws Exception {
        String projectPath = System.getProperty("user.dir");
        File file = new File(projectPath + LOCAT_FILE);
        if (!file.exists()) {
            System.err.println("本地文件未找到");
            return false;
        }
        Channel channel = sshSession.openChannel("sftp");
        channel.connect();
        ChannelSftp sftp = (ChannelSftp) channel;
        InputStream input = new BufferedInputStream(new FileInputStream(file));
        sftp.cd("/root");
        System.out.println("开始上传！");
        long startTime = System.currentTimeMillis();
        sftp.put(input, file.getName());
        long endTime = System.currentTimeMillis();
        System.out.println("文件上传成功！   上传时间：" + (endTime - startTime) + "ms");
        return true;
    }

    public static void runCmd(String cmd) throws Exception {
        System.out.println("开始执行命令：" + cmd);
        Channel channel = null;
        StringBuilder sb = new StringBuilder();
        InputStream in = null;
        channel = sshSession.openChannel("exec");
        ((ChannelExec) channel).setCommand(cmd);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err); // 获取执行错误的信息
        in = channel.getInputStream();
        channel.connect();
        byte[] b = new byte[1024];
        int size = -1;
        while ((size = in.read()) > -1) {
            System.out.print(new String(b, 0, size)); // 打印执行命令的所返回的信息
            sb.append(new String(b, 0, size));
        }
        in.close();
        channel.disconnect();
        System.out.println("指令操作成功！");
    }
}
